<template>
  <view>
    <!-- 1.0 收获地址信息 -->
    <view
      @click="chooseAddress"
      class="address"
    >
      <view
        class="address-info"
        v-if="addressInfo"
      >
        <view class="address-info-name-phone">
          <view>
            <text style="font-size:12px;">收货人：{{addressInfo.userName}}</text>
          </view>
          <view style="display:flex;align-items: center;">
            <text style="margin-right:36rpx;font-size:12px;">{{addressInfo.telNumber}}</text>
            <view class="iconfont-tap icon-jiantouyou"></view>
          </view>
        </view>
        <view class="address-info-detail-info">
          <text style="font-size:12px;">收货地址：{{addressInfo.detailAddress}}</text>
        </view>
      </view>
      <view
        class="address-add"
        v-else
      >
        <text style="font-size:12px;">+ 新增地址</text>
      </view>
      <view class="address-pic">
        <image src="/static/img/cart_border@2x.png" />
      </view>
    </view>
    <!-- 2.0 购买的商品列表 -->
    <view class="order-list">
      <block
        v-for="item in goodsList"
        :key="item.goods_id"
      >
        <view class="product-item">
          <navigator class="product-left">
            <image :src="item.goods_small_logo" />
          </navigator>
          <view class="product-right">
            <navigator class="product-name">
              {{item.goods_name}}
            </navigator>
            <view class="product-right-price">
              <text class="product-right-price-symbol">￥</text>
              <text class="product-right-price-integer">{{item.goods_price}}</text>
              <text class="product-right-price-decimal">.00</text>
            </view>
            <view class="product-right-num">x{{item.goods_number}}</view>
          </view>
        </view>
      </block>
    </view>
    <!-- 3.0 金额统计 -->
    <view class="order-total">
      <view class="order-total-item">
        <text>商品金额</text>
        <text class="order-total-item-price">￥{{totalAmount}}</text>
      </view>
      <view class="order-total-item">
        <text>运 费</text>
        <text class="order-total-item-price">￥+0.00</text>
      </view>
      <block v-if="token">
        <view
          @click="goToOrderAndPay"
          class="wxPay"
        >微信支付</view>
      </block>
      <block v-else>
        <button
          @getuserinfo="getuserinfo"
          open-type="getUserInfo"
          class="wxLogin"
        >登录后下单支付</button>
      </block>
    </view>
  </view>
</template>

<script>
import { getLocalGoods } from '../../utils/storage'

import LoginMixins from '../../mixins/LoginMixins'

export default {
  mixins: [LoginMixins],
  data() {
    return {
      addressInfo: null, //地址信息
      goodsList: [], //结算时，展示的用户信息
      totalAmount: 0, //总金额
      token: null, //是否登录的判断
      code: null //记录提前login的code值
    }
  },
  onLoad(options) {
    // 提前获取code
    // mpvue.login({
    //   success: ({ code }) => {
    //     this.code = code
    //   },
    //   fail: () => {},
    //   complete: () => {}
    // })

    // 加载商品数据
    this.getGoodsListData(options.ids)

    // 检测本地是否有数据
    if (mpvue.getStorageSync('address')) {
      this.addressInfo = mpvue.getStorageSync('address')
    }

    // 检查之前本地的登录token
    if (mpvue.getStorageSync('token')) {
      this.token = mpvue.getStorageSync('token')
    }
  },
  methods: {
    // 获取商品信息
    async getGoodsListData(ids) {
      const res = await this.$axios.get(`goods/goodslist?goods_ids=${ids}`)

      const localGoods = getLocalGoods()

      let totalAmount = 0
      res.data.message.forEach(item => {
        item.goods_number = localGoods[item.goods_id]
        totalAmount += item.goods_price * item.goods_number
      })

      this.totalAmount = totalAmount
      this.goodsList = res.data.message
    },
    // 选择收获地址
    chooseAddress() {
      mpvue.chooseAddress({
        success: res => {
          // 新增一个属性，用来记录详细地址
          res.detailAddress = `${res.provinceName}${res.cityName}${
            res.countyName
          }${res.detailInfo}`

          // 给当前的addressInfo赋值
          this.addressInfo = res

          // 存储起来，方便下次使用
          mpvue.setStorageSync('address', res)
        },
        fail: ({ errMsg }) => {
          if (errMsg === 'chooseAddress:fail auth deny') {
            //弹出一个模态框
            mpvue.showModal({
              showCancel: false,
              confirmColor: '#18a924',
              title: '提示',
              content: '请去我的页面打开授权',
              success: res => {
                mpvue.switchTab({ url: '/pages/mine/main' })
              }
            })
          }
        }
      })
    },
    getuserinfo(e) {
      this.wxLogin(e)
      /**
      // 用户拒绝了授权
      if (!e.mp.detail.errMsg === 'getUserInfo:ok') return

      // 保存个人信息到本地，方便在我的页面中进行获取
      mpvue.setStorageSync('userInfo',e.mp.detail.userInfo)

      // 2.调用mpvue.login获取临时的code
      mpvue.login({
        success: async res => {
          const result = await this.$axios.post('users/wxlogin', {
            code: res.code,
            encryptedData: e.mp.detail.encryptedData,
            iv: e.mp.detail.iv,
            rawData: e.mp.detail.rawData,
            signature: e.mp.detail.signature
          })

          // 给模型中的token赋值
          this.token = result.data.message.token

          // 保存到本地
          mpvue.setStorageSync('token', this.token)
        },
        fail: () => {},
        complete: () => {}
      })
       */
    },
    async goToOrderAndPay() {
      if (!this.addressInfo) {
        mpvue.showToast({
          title: '请选择收获地址', //提示的内容,
          icon: 'none', //图标,
          duration: 1000, //延迟时间,
          mask: true //显示透明蒙层，防止触摸穿透
        })
        return
      }

      // 生成请求参数
      const obj = {
        order_price: this.totalAmount,
        consignee_addr: this.addressInfo.detailAddress,
        goods: this.goodsList.map(item => {
          return {
            goods_id: item.goods_id,
            goods_number: item.goods_number,
            goods_price: item.goods_price
          }
        })
      }

      // 发送请求
      // const res = await this.$axios.post('my/orders/create', obj)

      // "HMDD20190403000000000708"
      this.pay('HMDD20190403000000000708')
    },
    async pay(order_number) {
      //1 调用后台的支付接口
      const res = await this.$axios.post('my/orders/req_unifiedorder', {
        order_number
      })

      mpvue.requestPayment({
        timeStamp: res.data.message.pay.timeStamp, // 时间戳
        nonceStr: res.data.message.pay.nonceStr, // 随机字符串
        package: res.data.message.pay.package, // 预付单信息
        signType: res.data.message.pay.signType, // 加密方式
        paySign: res.data.message.pay.paySign, // 签名
        success: async res => {
          // 调用后台接口，让后台把该笔订单的支付状态改为已经支付
          const result = await this.$axios.post('my/orders/chkOrder', {
            order_number
          })

          // 弹出一个提示框
          mpvue.showToast({
            title: '支付成功', //提示的内容,
            image: '/static/img/duigou.png', //图标,
            duration: 1500, //延迟时间,
            mask: true, //显示透明蒙层，防止触摸穿透,
            success: res => {
              setTimeout(() => {
                // 跳转到我的订单列表页面，并且 type = 3【待收货】
                mpvue.navigateTo({ url: '/pages/orders/main?type=3' })
              }, 1500)
            }
          })
        },
        fail: ({ errMsg }) => {
          // fail
          if (errMsg === 'requestPayment:fail cancel') {
            // 弹出一个提示框
            mpvue.showToast({
              title: '您取消了支付', //提示的内容,
              image: '/static/img/error2.png', //图标,
              duration: 1500, //延迟时间,
              mask: true, //显示透明蒙层，防止触摸穿透,
              success: res => {
                setTimeout(() => {
                  // 跳转到我的订单列表页面，并且 type = 2【待付款】
                  mpvue.navigateTo({ url: '/pages/orders/main?type=2' })
                }, 1500)
              }
            })
          } else {
            // 弹出一个提示框
            mpvue.showToast({
              title: '支付失败', //提示的内容,
              image: '/static/img/error2.png', //图标,
              duration: 1500, //延迟时间,
              mask: true, //显示透明蒙层，防止触摸穿透,
              success: res => {
                setTimeout(() => {
                  // 跳转到我的订单列表页面，并且 type = 2【待付款】
                  mpvue.navigateTo({ url: '/pages/orders/main?type=2' })
                }, 1500)
              }
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.address {
  height: 222rpx;
  background-color: #fff;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  &-info {
    display: flex;
    height: 160rpx;
    flex: 1;
    flex-direction: column;
    justify-content: space-around;
    &-name-phone {
      display: flex;
      justify-content: space-between;
      padding: 0rpx 30rpx;
    }
    &-detail-info {
      padding: 0rpx 30rpx;
    }
  }
  &-add {
    width: 360rpx;
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
    margin: 100px auto;
    color: #999;
    background-color: #f4f4f4;
  }
  &-pic {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 750rpx;
    height: 15rpx;
    image {
      width: 100%;
      height: 100%;
    }
  }
}
.iconfont-tap {
  font-family: 'iconfont' !important;
  font-size: 32rpx;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  min-width: 88rpx;
  min-height: 88rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}
.icon-jiantouyou {
  position: absolute;
  top: 32rpx;
  right: 0;
}
.icon-jiantouyou:before {
  font-size: 24rpx;
  color: #999;
  line-height: 1;
  width: 15rpx;
  height: 25rpx;
}
.order-list {
  background-color: #fff;
}
.product-item {
  display: flex;
  padding: 30rpx 20rpx;
  position: relative;
  &::after {
    content: '';
    position: absolute;
    left: 20rpx;
    right: 0;
    bottom: 0;
    border-bottom: 1rpx solid #ddd;
  }
  .product-left {
    width: 200rpx;
    height: 200rpx;
    background-color: #eee;
    margin-right: 26rpx;
    image {
      width: 100%;
      height: 100%;
    }
  }
  .product-right {
    width: 480rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    position: relative;
    .product-name {
      height: 84rpx;
      font-size: 30rpx;
      line-height: 1.4;
      /* 多行文字隐藏省略号 */
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
    }
    &-price {
      text {
        color: #ff2d4a;
      }
      &-symbol,
      &-decimal {
        font-size: 28rpx;
      }
      &-integer {
        font-size: 44rpx;
      }
    }
    &-num {
      position: absolute;
      right: 0;
      bottom: 0;
      letter-spacing: 2rpx;
      color: #999;
    }
  }
}
.order-total {
  background-color: #fff;
  margin-top: 20rpx;
  height: 300rpx;
  &-item {
    height: 80rpx;
    display: flex;
    align-items: center;
    padding: 0rpx 30rpx;
    justify-content: space-between;
    &-price {
      color: #ff2d4a;
    }
  }
}
.wxLogin {
  margin-top: 10rpx;
  width: 720rpx;
}
.wxPay {
  margin-top: 10rpx;
  margin-left: 15rpx;
  width: 720rpx;
  background-color: #00c000;
  display: flex;
  height: 80rpx;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-size: 32rpx;
  border-radius: 5rpx;
}
</style>

